package com.stu.widget;

import com.stu.aq.AQ;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class HorScaleView extends View {
	private Paint textPaint, linePaint;
	private int tickDx, tickCount, majorY1, majorY2,
	  minorY1, minorY2, textX1, lineX1;
	private final static int textSize=12, majorSize=15, minorSize=10, minHeight=20, minWidth=100, resolution=100;
	private Rect textRect;

	public HorScaleView(Context context) {
		super(context);
		init();
	}

	public HorScaleView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public HorScaleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		tickCount = ((AQ.motorMax - AQ.motorMin) / resolution) + 1;
		textPaint = new Paint();
		textPaint.setColor(Color.BLACK);
		textPaint.setTextAlign(Align.CENTER);
		textPaint.setTextSize( textSize );

		textRect = new Rect();
		String s = "1000";
		textPaint.getTextBounds( s, 0, s.length(), textRect );
		majorY1 = minHeight - textRect.height() - majorSize;
		majorY2 = minHeight - textRect.height();
		minorY1 = minHeight - textRect.height() - minorSize;
		minorY2 = minHeight - textRect.height();

		linePaint = new Paint();
		linePaint.setColor(Color.BLACK);
		linePaint.setStyle(Paint.Style.STROKE);

		lineX1 = textRect.width() / 2;
		textX1 = lineX1;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
		setMeasuredDimension(minWidth + textRect.width(), minHeight);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		int width = getWidth();
		int height = getHeight();
		tickDx = (width - textRect.width()) / tickCount;
		int lineX = lineX1;
		int textX = textX1;
		for( int i = AQ.motorMin; i <= AQ.motorMax; i += resolution ) {
			if( (i % 500) == 0 ) {
				canvas.drawText( String.valueOf(i), textX, height, textPaint );
				linePaint.setStrokeWidth( 2 );
				canvas.drawLine( lineX, majorY1, lineX, majorY2, linePaint );
			} else {
				linePaint.setStrokeWidth( 1 );
				canvas.drawLine( lineX, minorY1, lineX, minorY2, linePaint );
			}
			lineX += tickDx;
			textX += tickDx;
		}
	}

}
